/**
 * Created by coder on 2018/1/11.
 */
import initState from './state'
import {ACTION_UNDO,ACTION_REDO,ACTION_MEMORY_RESET,ACTION_ADD_MEMORY} from './action'

export default (state = initState.memory,action) => {
	switch (action.type){
		case ACTION_UNDO:
			if(state.undo.length){
				let newUndo = state.undo.slice();
				let newRedo = state.redo.slice();
				newRedo.push(state.cur);
				let newCur = newUndo.pop();
				return {
					undo:newUndo,
					redo:newRedo,
					cur:newCur,
				};
			}
			break;
		case ACTION_REDO:
			if(state.redo.length){
				let newUndo = state.undo.slice();
				let newRedo = state.redo.slice();
				newUndo.push(state.cur);
				let newCur = newRedo.pop();
				return {
					undo:newUndo,
					redo:newRedo,
					cur:newCur,
				};
			}
			break;
		case ACTION_MEMORY_RESET:
			return {undo:[],redo:[],cur:null};
		case ACTION_ADD_MEMORY:
			const {cells} = action.payload;
			if(state.cur === null){
				return Object.assign({},state,{cur:cells});
			} else {
				let newUndo = state.undo.slice();
				newUndo.push(state.cur);
				return {undo:newUndo,redo:[],cur:cells};
			}
		default:
			return state;
	}
}